package com.hitplane.manager 
{
	import com.hitplane.debug.DebugTrace;
	import com.hitplane.interfaces.ILayoutAble;
	import flash.display.DisplayObject;
	import flash.events.Event;

	/**
	 * 布局管理
	 * 单例模式类
	 * @author 郑子华
	 */
	public class LayoutManager
	{
		private static var _instance:LayoutManager = null;
		public function LayoutManager(single:Single) 
		{
			
			if(single == null)
			{
				throw new Error("Can't create instance , Single is Null!");
			}
			
			GameContainManager.instance.mainStage.addEventListener(Event.RESIZE, onStageSize);
		}
		/**
		 * 单例引用
		 */
		public static function get instance():LayoutManager
		{
			if(_instance == null)
			{
				_instance = new LayoutManager(new Single());
			}
			return _instance;
		}
		
		//参与布局的集合
		private var _layoutArr:Array = [];
		
		public function registerLayoutObj(layoutInstance:ILayoutAble):void {
			var index:int = _layoutArr.indexOf(layoutInstance);
			if (index == -1) {
				_layoutArr.push(layoutInstance);
			}else {
				DebugTrace.traceObj(this, "layoutInstance已经注册。");
			}
		}
		public function removeLayoutObj(layoutInstance:ILayoutAble):void {
			var index:int = _layoutArr.indexOf(layoutInstance);
			if (index == -1) {
				DebugTrace.traceObj(this, "没有该对象");
			}else {
				_layoutArr.splice(index, 1);
			}
		}
		/**
		 * 舞台大小改变
		 * @param	e
		 */
		private function onStageSize(e:Event):void {
			var stageW:int = GameContainManager.instance.mainStage.stageWidth;
			var stageH:int = GameContainManager.instance.mainStage.stageHeight;
			for each (var item:ILayoutAble in _layoutArr) 
			{
				reposition(item,stageW,stageH);
			}
		}
		/**
		 * 重新布局
		 * @param	layoutObj
		 */
		private function reposition(layoutInstance:ILayoutAble, stageW:int, stageH:int):void {
			var x:int = layoutInstance.layoutObj.x;
			var y:int = layoutInstance.layoutObj.y;
			var offsetX:int = layoutInstance.layoutObj.offsetX;
			var offsetY:int = layoutInstance.layoutObj.offsetY;
			(layoutInstance as DisplayObject).x = x * stageW + offsetX;
			(layoutInstance as DisplayObject).y = y * stageH + offsetY;
		}
	}
}
class Single{}